package nix.demo4.web.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class AFilter implements Filter {

	private FilterConfig fConfig;

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 获得ServletContext
		ServletContext application = this.fConfig.getServletContext();
		Map<String, Integer> map = (Map<String, Integer>) application.getAttribute("map");
		// 获取客户端IP，计数
		String ip = request.getRemoteAddr();
		if (map.containsKey(ip)) {
			map.put(ip, map.get(ip) + 1);
		} else {
			map.put(ip, 1);
		}
		application.setAttribute("map", map);
		// 放行
		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		this.fConfig = fConfig;
	}

}
